﻿using System;
using System.Resources;
using System.Collections.Generic;

namespace Useful.Localization
{
    public class Localizator
    {
        private readonly object lockObj = new object();

        private static Localizator instance = null;
        public static Localizator Instance
        {
            set
            {
                instance = value;
            }
        }

        protected virtual string ResourcesFileString
        {
            get
            {
                //return "Localization.Resources.resources";
                return null;
            }
        }

        private ResourceManager rm = null;
        private readonly Dictionary<string, string> dictResources = new Dictionary<string, string>();

        public static string GetString(string inStr)
        {
            if (instance != null)
                return instance.GetStringCore(inStr);
            else
                return inStr;
        }

        private ResourceManager Resources
        {
            get
            {
                if (rm == null)
                    rm = new ResourceManager(ResourcesFileString, typeof(Localizator).Assembly);

                return rm;
            }
        }

        private string GetStringCore(string inStr)
        {
            string res;

            if (!String.IsNullOrEmpty(inStr))
            {
#if LOCK_DICT
                lock (lockObj)
#endif
                {
                    if (!dictResources.TryGetValue(inStr, out res))
                    {
                        try
                        {
                            string findStr = inStr.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n");

                            res = Resources.GetString(findStr);

                            if (String.IsNullOrEmpty(res))
                                res = inStr;
                        }
                        catch
                        {
                            res = inStr;
                        }

                        dictResources.Add(inStr, res);
                    }
                }
            }
            else
                res = inStr;

            return res;
        }
    }
}
